const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();
// pages/order/pay.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    address_detail: {
      region: "广东省深圳市福田区华强北街道",
      name: "裴一聪",
      address: '公寓333',
      phone: '13972038056',
    },
    cart_list: [],
    list: [],
    type: '',
    uid: 0,
    title_name: '订单详情',
    if_address: false,
    if_show_box: false,
    if_show_mask: false,
    if_show_box_delivery: false,
    address_list: [],
    delivery_list: [],
    if_has_default: false,
    chosen_id: 0,
    chosen_id_delivery: 0,
    if_show_end_paying_box: false,
    number: 0,
    total_price: 0,
    options: {},
    if_use_ticket: false,
    good_id: '',
    myinfo_data: {},
  },

  onUnload() { },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init_data(options)
    this.get_address_list()
    this.get_address()
    this.get_delivery_list()
    this.get_myinfo()
  },

  init_data(options) {
    this.setData({
      uid: util.getAppValue(App.globalData.uid),
      options
    })

    let type = options.type
    // console.log(type);
    this.setData({
      type,
    })

    // type==1，用户直接从商品详情里购买单个商品
    // type==10 用户积分兑换单个商品
    if (type == 1 | type == 10) {
      this.setData({
        good_id: options.good_id,
        entrance: type == 1 ? "normal" : 'costpoint'
      })
      let params = {
        uid: this.data.uid,
        id: options.good_id,
      }
      request.post(api.goods_details, params).then(res => {
        let list = []
        list.push(res)
        list[0].goods_num = 1
        this.setData({
          cart_list: list
        })
        this.counting_price()
      })
    }
    // type=7，用户从购物车购买商品
    else {
      let params = {
        uid: this.data.uid
      }
      request.post(api.cart_list, params).then(res => {
        this.setData({
          cart_list: res
        })
        this.counting_price()
      })
    }
  },

  get_myinfo() {
    let params = {
      uid: this.data.uid,
    }
    request.post(api.myinfo, params).then(res => {
      this.setData({
        myinfo_data: res
      })
    })
  },

  minus(e) {
    let index = e.currentTarget.dataset.index
    let cart_list = this.data.cart_list
    cart_list[index].goods_num = --cart_list[index].goods_num
    this.setData({
      cart_list
    })
    this.counting_price()
  },

  plus(e) {
    let index = e.currentTarget.dataset.index
    let cart_list = this.data.cart_list
    cart_list[index].goods_num = ++cart_list[index].goods_num
    this.setData({
      cart_list
    })
    this.counting_price()
  },

  go_edit(e) {
    let url = '/pages/address/edit?address_id=' + e.currentTarget.dataset.id + '&type=' + this.data.type + '&good_id=' + this.data.good_id
    wx.navigateTo({
      url,
    })
  },

  get_delivery_list() {
    let params = {

    }
    request.post(api.takeselflist, params).then(res => {
      this.setData({
        delivery_list: res
      })
    })
  },

  // 根据defalut，或者[0],获取顶部页面的地址信息
  get_address() {
    let params = {
      uid: this.data.uid
    }
    request.post(api.addresslist, params).then(res => {
      if (res.length != 0) {
        this.setData({
          if_address: true
        })
      }
      // 查找是否有默认地址
      for (let i of res) {
        if (i.is_default) {
          this.setData({
            address_detail: i,
            if_address: true,
            aid: i.id,
            chosen_id: i.id,
          })
        }
      }
      // 如果地址列表里有地址但没有默认的
      if (this.data.if_address) {
        this.setData({
          address_detail: res[0],
          if_address: true,
          aid: res[0].id,
          chosen_id: res[0].id
        })
      }
    })
  },

  go_add_address() {
    let url = '/pages/address/add?type=' + this.data.type + '&good_id=' + this.data.good_id
    wx.navigateTo({
      url,
    })
  },

  change_address(e) {
    let chosen_id = e.currentTarget.dataset.id
    this.setData({
      chosen_id,
      chosen_id_delivery: 0
    })
    this.get_address_detail(chosen_id)
  },

  change_delivery(e) {
    let chosen_id_delivery = e.currentTarget.dataset.id
    this.setData({
      chosen_id_delivery,
      chosen_id: 0,
      if_address: true
    })
    this.get_delivery_detail(chosen_id_delivery)
  },

  counting_price() {
    let type = this.data.type
    let number = 0
    let total_price = 0
    for (let i = 0; i < this.data.cart_list.length; i++) {
      let goods_num = this.data.cart_list[i].goods_num
      let single_price = util.accMul(this.data.cart_list[i].sell_price, goods_num)
      // let single_price = this.data.cart_list[i].sell_price * goods_num
      total_price += single_price
      number += goods_num
    }
    let submit_price = total_price
    if (this.data.if_use_ticket) {
      submit_price -= 3
    }
    console.log(submit_price);
    this.setData({
      total_price,
      number,
      submit_price,
    })
  },

  // 根据所选自提点，更改页面顶部地址
  get_delivery_detail(id) {
    util.showLoading('正在更改地址')
    let params = {
      id
    }
    request.post(api.takeselfdetail, params).then(res => {
      this.setData({
        address_detail: res
      })
      util.hideLoading(0)
    })
  },

  // 根据所选地址，更改页面顶部地址
  get_address_detail(id) {
    util.showLoading('正在更改地址')
    let params = {
      id
    }
    request.post(api.addressdetail, params).then(res => {
      this.setData({
        address_detail: res
      })
      util.hideLoading()
    })
  },

  // 获取box里的地址列表
  get_address_list() {
    let params = {
      uid: this.data.uid
    }
    request.post(api.addresslist, params).then(res => {
      this.setData({
        address_list: res
      })
    })
  },

  choose_address() {
    this.setData({
      if_show_box: true,
    })
  },

  choose_delivery() {
    this.setData({
      if_show_box_delivery: true,
      if_show_mask: true
    })
  },

  clear_mask() {
    this.setData({
      if_show_box: false,
      if_show_mask: false,
      if_show_end_paying_box: false,
      if_show_box_delivery: false
    })
  },

  clear_mask_delivery() {
    this.setData({})
  },

  get_post_data_type(post_data, type) {
    // type=2，用户直接从商品详情里购买单个商品
    if (type == 2) {
      post_data.id = this.data.good_id
    }
    // type=10，用户使用积分兑换购买单个商品
    if (type == 10) {
      post_data.id = this.data.good_id
    }
    // type=7，用户从购物车购买商品,后台会直接读取cartlist里的商品内容，在支付后会清空cartlist。
    if (type == 7) {

    }
    return post_data
  },

  get_post_data_address(post_data) {
    let chosen_id = this.data.chosen_id
    let chosen_id_delivery = this.data.chosen_id_delivery
    if (chosen_id != 0 && chosen_id_delivery == 0) {
      post_data.aid = chosen_id
    }
    if (chosen_id == 0 && chosen_id_delivery != 0) {
      post_data.takeself = chosen_id_delivery
    }
    // console.log(post_data);
    return post_data
  },

  // 1.开始支付，支付流程是先调用orderadd生成一个订单，输出一个订单号
  // 2.输入一个订单号，调用orderpay，输出微信支付所需要的签名信息
  // 3.输入签名信息，调用微信的支付接口，完成支付后跳转页面，在此期间可修改订单的状态status
  paying() {
    // 检查用户是否选取了地址
    const that = this;

    if (!this.data.if_address) {
      util.showToast('请选择一个地址')
      return
    }

    let type = this.data.type
    // 基本的请求参数信息
    let post_data = {
      uid: this.data.uid,
      type,
      goods_id: this.data.good_id,
    }

    // 根据不同的type来修改对应的请求参数
    post_data = this.get_post_data_type(post_data, type)

    // 根据用户是用自选的地址，还是自提点的地址，来调整请求参数
    post_data = this.get_post_data_address(post_data)

    // 开始支付流程
    if (this.data.entrance == 'costpoint' && this.data.cart_list[0].point > this.data.myinfo_data.point) {
      util.showToast('积分不足');
      return
    }

    request.post(api.orderadd, post_data).then(res => {
      let post_data = {
        id: res,
        order_no: res.order_no
      }

      // 根据用户是用自选的地址，还是自提点的地址，来调整请求参数
      post_data = this.get_post_data_address(post_data)
      if (this.data.entrance == "costpoint") {
        util.showSuccess('兑换成功');
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/point',
          })
        }, 1000);
        return
      }

      request.post(api.orderpay, post_data).then(res => {
        this.wx_pay(res)
      })
    })
  },

  wx_pay(res) {
    console.log('微信官方支付接口');
    let post_data = res
    // wx.requestSubscribeMessage({
    //   tmplIds: ["gzVSi_MOPG3zbEXkZs9RSeZVhRZP5j91EpwfzrXnOOE", "zdQ1Tv9ML45xskYXpl_3KV_uiLsDoE1XpASrkLzY9XI","2H1XUJ10sCTPHa3RP4innq9abbWf6QZKw1Ppz4qL34o"],
    //   success: res=>{
    wx.requestPayment({
      nonceStr: post_data.nonceStr,
      package: post_data.package,
      paySign: post_data.paySign,
      timeStamp: post_data.timeStamp,
      signType: post_data.signType,
      success(res) {
        util.showSuccess('开通成功');
        wx.reLaunch({
          url: '/pages/order/pay_success',
        })
      },
      fail(e) {
        util.showToast('开通取消');
      }
    })
    //   },
    //   fail: e=>{
    //   }
    // })
  },
  go_vip() {
    let url = '/pages/vip/vip'
    wx.navigateTo({
      url,
    })
  },
  go_ticket() {
    let url = '/pages/ticket/ticket'
    wx.navigateTo({
      url,
    })
  },

  go_back() {
    this.setData({
      if_show_mask: true,
      if_show_end_paying_box: true
    })

  },

  continue_paying() {
    this.setData({
      if_show_end_paying_box: false
    })
    this.clear_mask()
  },

  stop_paying() {
    wx.switchTab({
      url: '/pages/onlineshop'
    })
  },

  wx_choose_address() {
    wx.chooseAddress({
      success: (result) => {
        let params = {
          uid: this.data.uid,
          name: result.userName,
          mobile: result.telNumber,
          province_name: result.provinceName,
          city_name: result.cityName,
          region_name: result.countyName,
          address: result.detailInfo,
          is_default: 0
        }
        request.post(api.addressadd, params).then(res => {
          this.onLoad(this.data.options)
        })
      },
    })
  },

  onShow: function () { },

})